import * as bcrypt from 'bcryptjs';
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { SearchUserDto } from './dto/search-user-dto';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { SysUserRole } from './entities/user-with-role.entity';
import { Result } from 'src/utils/result';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userEntity: Repository<User>,

    @InjectRepository(SysUserRole)
    private readonly userWithRoleEntity: Repository<SysUserRole>,
  ) {}
  // 新建用户
  async create(createUserDto: CreateUserDto) {
    createUserDto.password = await bcrypt.hash(createUserDto.password, 8);
    const user = await this.userEntity.save(createUserDto);
    const entity = await this.userWithRoleEntity.createQueryBuilder('entity');
    const values = createUserDto.roleIds.map((roleId) => ({
      roleId,
      userId: user.userId,
    }));
    await entity.insert().values(values).execute();
    return Result.success();
  }

  // 查询所有用户
  async findAll() {
    const list = await this.userEntity.find();
    return Result.success(list);
  }

  // 分页查询用户
  async findAllByPaging(query: SearchUserDto) {
    const userBuilder = this.userEntity.createQueryBuilder();
    userBuilder.skip((query.pageNum - 1) * query.pageSize).take(query.pageSize);
    const [list, total] = await userBuilder.getManyAndCount();

    return Result.success({ list, total });
  }
  // 通过用户名查询
  async findOneByName(username: string) {
    return await this.userEntity.findOne({
      where: {
        username,
      },
      select: ['userId', 'password'],
    });
  }
  // 查找单个信息
  async findOne(userId: number) {
    const user = await this.userEntity.findOneBy({
      userId,
    });
    const roleIds = await this.userWithRoleEntity.find({
      where: {
        userId,
      },
      select: ['roleId'],
    });
    return Result.success({
      ...user,
      roleIds: roleIds.map((item) => item.roleId),
    });
  }
  // 修改用户
  async update(userId: number, updateUserDto: UpdateUserDto) {
    const hasRole = await this.userWithRoleEntity.findOne({
      where: { userId },
    });
    if (hasRole) {
      this.userWithRoleEntity.delete({ userId });
    }
    const userRoleBuilder =
      this.userWithRoleEntity.createQueryBuilder('entity');
    const values = updateUserDto.roleIds.map((roleId) => ({
      userId,
      roleId,
    }));
    delete updateUserDto.roleIds;
    await this.userEntity.update(userId, updateUserDto);
    await userRoleBuilder.insert().values(values).execute();
    return Result.success();
  }

  // 删除用户
  async remove(id: number) {
    await this.userEntity.delete(id);
    const hasUser = await this.userWithRoleEntity.findOne({
      where: { userId: id },
    });
    if (hasUser) {
      await this.userWithRoleEntity.delete({ userId: id });
    }
    return Result.success();
  }
}
